﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace Lesson01_同步_服务端
{
    class Program
    {
        static void Main(string[] args)
        {
            //1.创建套接字Socket(TCP)
            Socket socketTcp = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //2.用Bind方法将套接字与本地地址绑定
            try
            {
                IPEndPoint ipPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8080);
                socketTcp.Bind(ipPoint);
            }
            catch (Exception e)
            {
                Console.WriteLine("绑定报错:" + e.Message);
                return;
            }
            //3.用Listen方法监听
            socketTcp.Listen(1024);
            Console.WriteLine("服务器端绑定监听结束,等待客户端连接.");
            //4.用Accept方法等待客户端连接
            //5.建立连接, Accept返回新套接字(阻塞)
            Socket socketClient = socketTcp.Accept();
            //6.用Send和Receive相关方法收发数据
            //发送
            socketClient.Send(Encoding.UTF8.GetBytes("欢迎连入服务端"));
            //接收数据
            byte[] result = new byte[1024];
            int recvLen = socketClient.Receive(result);
            Console.WriteLine("接收到了{0}发来的数据:{1}",
                    socketClient.RemoteEndPoint.ToString(),
                    Encoding.UTF8.GetString(result, 0, recvLen));
            //7.用Shutdown方法释放连接
            socketClient.Shutdown(SocketShutdown.Both);
            //8.关闭套接字
            socketClient.Close();

        }
    }
}